package android.tusnotas.core;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.XPatherException;

import android.tusnotas.beans.News;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.parser.news.NewsParser;
import android.tusnotas.util.Devel;
import android.util.Log;

public class NewsAnalyser {
	private WebServiceCaller caller = new WebServiceCaller();

	private int ttt = 5;//times to try before giving up connection try
	
	public List<News> doGetNews(String aulaID) throws RemoteReadingException, ProcessingInstancesException{
		String XML = doGetRemoteMoreInfoCouse(aulaID);
		List<News> newsList = doObtainNews(XML);
		return newsList;
	}
	
	private List<News> doObtainNews(String XML) throws ProcessingInstancesException{
		List<News> newsList = null;
		
		NewsParser newsParser = new NewsParser();
		
		try {
			newsList = newsParser.parseXML(XML);
		} catch (XPatherException e) {
			e.printStackTrace();
			throw new ProcessingInstancesException();
		}
		if(newsList == null){
			newsList = new ArrayList<News>();
		}
		return newsList;
	}
	
	private String doGetRemoteMoreInfoCouse(String aulaID) throws RemoteReadingException{

		String XML="";

		try {
			caller.SetForMoreInfoCouse(aulaID);
			XML = persistentCaller();
		} catch (Exception e){
			if( Devel.fullDevel){
				Log.w(this.getClass().getName(), "ERROR WHILE CONNECTING TO WC");
			}
			RemoteReadingException rwce = new RemoteReadingException();
			rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
			throw rwce;
		}

		return XML;
	}
	
	private String persistentCaller() throws RemoteReadingException{	
		while( ttt > 0){
			try{
				String XML = caller.execute();
				return XML;
			}catch(RemoteReadingException e){}
			ttt--;
		}
		throw new RemoteReadingException();

	}


}
